<?php

require_once('GenusAPIs/GenusApis.php');
session_start();
header('Content-Type: text/html; charset=utf-8');

// Url of this script.
define("SCRIPT_URL", "http://www.club-connect.nl/hyvessync/authorization_step1.php");

ob_start();
// Declare oauth_consumer
$oOAuthConsumer = new OAuthConsumer("MjEwNV-jK9CigmbdQ_zJa-FU8qDy", "MjEwNV_8vv9S3vRZwSLVItIrsZwu");

// Init GenusApis
$oGenusApis = new GenusApis($oOAuthConsumer);

// Application
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>Authorization Hyves</title>
</head>
<body>
<?php
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : "default";
switch($action) 
{
	case 'default':
		// Default page
		echo "<a href=\"".SCRIPT_URL."?action=authorize\">Authorize</a><br />";
		break;
	case 'authorize':
		// Create request token and authorize it (causes redirect).
		$oRequestToken = $oGenusApis->retrieveRequesttoken(array("friends.get", "users.get", "media.getAlbums", "wwws.create"));
		$_SESSION['requesttoken_'.$oRequestToken->getKey()] = serialize($oRequestToken);
		$oGenusApis->redirectToAuthorizeUrl($oRequestToken, SCRIPT_URL."?action=authorized");
		break;
	case 'authorized':
		// Authorized page, hyves will redirect to this page (callback).
		$oauth_token = $_REQUEST['oauth_token'];
		$oRequestToken = getRequestTokenFromSession($oauth_token);
		$oAccessToken = $oGenusApis->retrieveAccesstoken($oRequestToken);
		$sAccessToken = serialize($oAccessToken);
		$userid = (string) $oAccessToken->getUserid();
		$oXML = $oGenusApis->doMethod("users.get", array("userid" => "$userid"), $oAccessToken);
		$voornaam = $oXML->user->firstname;
		// Write authorization header to database
						require_once("database_inc.php");
						$db = mysqli_connect($server,$gebruikersnaam,$password);
						mysqli_select_db($db, $database);
						$sql = "INSERT INTO users (gebruikersID, voorNaam, googleAuthSubToken, hyvesID, hyvesAccessTokenObject) VALUES (NULL, '".$voornaam."', NULL,
						'".$userid."', '".$sAccessToken."')";
						mysqli_query($db, $sql);
					    // Fetch userID for next step in registration
					    $sql = "SELECT * FROM users WHERE hyvesID = '".$userid."'";
						$result = mysqli_query($db, $sql);
						$regel = mysqli_fetch_array($result);
						$_SESSION['gebruikersID'] = $regel['gebruikersID'];
						$_SESSION['hyvesid'] = $regel['hyvesID'];
						header('Location: authorization_step2.php');
		break;
}

// example storage for requesttoken
function getRequestTokenFromSession($oauth_token) {
	if (!isset($_SESSION['requesttoken_'.$oauth_token])) {
		header("Location: ".SCRIPT_URL."?action=invalidsession");
	}
	return unserialize($_SESSION['requesttoken_'.$oauth_token]);
}
?>
</body>
</html>